<template>
    <div class="dashboard-container">

      <!-- 顶部操作栏 -->
      <div class="search">
        <el-form :inline="true" class="left">
          <el-form-item>
            <el-button type="primary" @click="handleAdd('create')">
              <i class="el-icon-plus"></i>
              新增
            </el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="danger" @click="getData">
              <i class="el-icon-delete-solid"></i>
              删除
            </el-button>
          </el-form-item> -->
        </el-form>
        <el-form :inline="true" :model="params" class="right">
          <el-form-item>
            <el-input placeholder="请输入枚举类型名称" v-model="params.name" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleSearch">
              查询
              <i class="el-icon-search"></i>
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 内容栏 -->
      <div class="body">
        <!-- 列表 -->
        <el-table :data="list" v-loading="loading">
          <el-table-column label="名称" prop="name"></el-table-column>
          <!-- <el-table-column label="评估对象类型" prop="objectType"></el-table-column>
          <el-table-column label="资产类型" prop="propertyType"></el-table-column> -->
          <el-table-column label="操作">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleLook(row.id)">
                <i class="el-icon-edit-outline"></i>
                查看子项
              </el-button>
              <el-button type="text" @click="handleAdd('update', row)">
                <i class="el-icon-edit-outline"></i>
                编辑
              </el-button>
              <el-button type="text" @click="handleDelete(row)" style="color: red;">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex+1"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageCount"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>

      <!-- 子项显示 -->
      <el-dialog
          :visible="dialogVisible" 
          title="详情" 
          :close-on-click-modal="false"
          @close="dialogVisible=false"
          width="600px"
      > 
          <div style="margin-bottom: 10px;">
            <el-button type="primary" size="mini" @click="handleAddItem('create')"><i class="el-icon-plus" ></i>新增</el-button>
          </div>
          <el-tree
            :data="treeData"
            node-key="id"
            :expand-on-click-node="false"
            :render-content="renderContent"
          >
          </el-tree>

          <el-form ref="form">
              <el-form-item>
                  <el-button @click="dialogVisible = false" size="mini">关闭</el-button>
              </el-form-item>
          </el-form>
      </el-dialog>


      <!-- 新增、编辑子项 -->
      <el-dialog 
        :title="dialogType=='create'?'新增项':'编辑项'"
        :visible="dialogVisibleItem" 
        :close-on-click-modal="false"
        @close="dialogVisibleItem=false"
        width="800px"
      >
        <el-form v-model="temp" ref="itemForm" size="mini" label-width="100px">
          <el-form-item label="枚举名" required>
            <el-input placeholder="请输入枚举名称" v-model="temp.name"></el-input>
          </el-form-item>
          <el-form-item label="可选">
            <el-select v-model="temp.selectFlag" placeholder="可选" size="mini">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="扩展字段">
            <el-input placeholder="请输入扩展字段，’abc=123|edf=456.0’" v-model="temp.extendValues"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input placeholder="请输入描述" v-model="temp.description"></el-input>
          </el-form-item>
          <el-form-item label="排序值">
            <el-input placeholder="请输入排序值" v-model="temp.sortValue"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="submitAddItem">提交</el-button>
          <el-button @click="dialogVisibleItem = false">关闭</el-button>
        </div>
      </el-dialog>

    </div>
</template>
  
<script>
import { mapGetters } from 'vuex'
import { enumGetList, enumInfo, enumDelete, enumCreateItem, enumDeleteItem, enumUpdateItem } from '@/api/enum'
import moment from 'moment'
import { transfromData } from '@/utils/tools';
import { TARGET_TYPE_LIST, OBJECT_ALL_TYPE_LIST } from '@/utils/common'
  
export default {
    name: 'StaffEnum',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return {
        TARGET_TYPE_LIST,
        rules: {
          name: [{ required: true, message: '请输入枚举类型名称', trigger: 'blur' }],
          propertyType: [{ required: true, message: '请选择评估对象', trigger: 'blur' }],
        },
        params: {
          companyId: 1,
          pageCount: 10,
          pageIndex: 0,
          name: '',
          systemFlag: 0
        },
        total: 0,
        list: [],
        dialogVisible: false,
        dialogType: 'create',
        temp: {
          name: '',
          enumId: '',
          selectFlag: 1
        },
        loading: false,
        treeData: [],
        dialogVisibleItem: false,
      }
    },
    mounted(){
      this.handleSearch();
    },
  
    methods:{
      //提交添加
      async submitAddItem(){
        if(this.dialogType == 'create'){
          await enumCreateItem(this.temp);
        }else{
          this.temp.enumItemId = this.temp.id;
          await enumUpdateItem(this.temp);
        }
        
        this.$message.success({ message: '提交成功' })
        this.dialogVisibleItem = false;
        this.handleLook(this.temp.enumId)
      },
      // 树结构，拓展点击按钮
      renderContent(h, { node, data, store }) {
            return (
            <span class="custom-tree-node">
                <span style="margin-right: 10px;">{node.label}</span>
                <span>
                {data.selectFlag==0?<el-button size="mini" type="text" style="margin-left: 10px;" on-click={ () => this.handleAddItem('create',data) }>新增</el-button>: ''}
                <el-button size="mini" type="text" on-click={ () => this.handleAddItem('update', data) }>编辑</el-button>
                <el-button size="mini" style="color: red" type="text" on-click={ () => this.remove(node, data) }>删除</el-button>
                </span>
            </span>);
      },
      //删除子项
      async remove(node, data) {
            await enumDeleteItem({ enumItemId: data.id })
            const parent = node.parent;
            const children = parent.data.children || parent.data; 
            const index = children.findIndex(d => d.id === data.id);
            children.splice(index, 1);
      },
      //点击添加子项
      async handleAddItem(type, data){
        this.dialogType = type;
        this.dialogVisibleItem = true;
        if(type=='create'){
          
          let parentId = '';
          if(data){
            parentId = data.id
          }
          this.temp = {
            name: '',
            enumId: this.temp.enumId,
            selectFlag: 1,
            extendValues: '',
            parentId: parentId,
            sortValue: 0,
            description: ''
          };
        }else{
          let { id, label, parentId, selectFlag, extendValues, sortValue, description } = data;
          this.temp = {
            id, name: label, parentId, selectFlag, extendValues, sortValue, description
          }
        }
      },  
      //点击删除
      handleDelete(row){
        this.$confirm('此操作将永久删除该枚举, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await enumDelete({ id: row.id })
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //查询子项
      async handleLook(id){
        this.temp.enumId = id;
        this.treeData = [];
        let data = await enumInfo({ id })
        for(let i = 1; i<10; i++){
                let arr = data.items.filter(item=>item.level==i).map(item=>{
                  let { name, id, parentId, selectFlag, extendValues, sortValue, description } = item;
                  return { children: [], id, label: name, parentId, selectFlag, extendValues, sortValue, description };
                });
                // 遇到这个层级没有数据的，直接跳出
                if(arr.length==0)break;
                //循环这个层级;
                arr.forEach(aItem=>{
                    if(i==1){
                        this.treeData.push(aItem)
                    }else{
                        this.treeData = this.treeData.map(dItem=>{
                            if(dItem.id==aItem.parentId){
                                dItem.children.push(aItem)
                            }
                            return dItem;
                        })
                    }
                })
        }
        this.dialogVisible = true;
      },
      // 点击新增、编辑
      handleAdd(type, row){
        if(type=='create'){
            this.$router.push({ path: '/data/enumAdd' })
        }else{
          this.$router.push({ path: '/data/enumAdd?id='+row.id })
        }
      },
      //修改搜索条件
      handleSearch(){
        this.params.pageIndex = 0;
        this.getData();
      },
      //加载列表数据
      async getData(){
        this.loading = true
        let data = await enumGetList(this.params)
        this.loading = false;
        this.total = data.totalCount;
        this.list = data.list.map(item=>{
          item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
          item.objectType =  transfromData(OBJECT_ALL_TYPE_LIST, item.objectType)
          item.propertyType = transfromData(TARGET_TYPE_LIST, item.propertyType)
          return item;
        });
      },
      // 修改每页数量
      handleSizeChange(val){
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
      },
      // 切换分页
      handleCurrentChange(val){
        this.params.pageIndex = val - 1;
        this.getData();
      }
    }
}
</script>
  
<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .right{
        position: absolute;
        right: 0;
        top: 0;
      }

      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  